6kyu
Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (like the name of this kata).
Strings passed in will consist of only letters and spaces.
Spaces will be included only when more than one word is present.
Example:
spinWords("Hey fellow warriors") => "Hey wollef sroirraw"
spinWords("This is a test") => "This is a test"
spinWords("This is another test") => "This is rehtona test"
中翻:字串中任何一個字的長度大於或等於5時則反轉該字,反之則輸出一樣的字。
export class Kata {
static spinWords(words: string) {
let arr = words.split(" ");
arr.forEach((e,index) => {
if(e.length >= 5 ){
let reverse = e.split('').reverse().join('');
arr.splice(index,1,reverse)
}
})
return arr.join(" ")
}
}
概念:
author: joewoodhouse
export class Kata {
static spinWords(words: string) {
return words
.split(' ') // Split words up
.map((w: string) => w.length >= 5 ? w.split('').reverse().join('') : w)
.join(' '); // Put them back together
}
}
透過一連串方法,一次將資料處理完畢後直接回傳,非常精簡~
補充w.length >= 5 ? w.split('').reverse().join('') : w
此寫法為Ternary Operator (三元運算子)
,可以將if else精簡表達出來,有興趣的可以查看看
https://catforcode.com/ternary-operators/
array.split()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
array.splice() 可以藉由刪除既有元素並/或加入新元素來改變一個陣列的內容。
https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
(另外補充)三種reverse string的方法
https://www.freecodecamp.org/news/how-to-reverse-a-string-in-javascript-in-3-different-ways-75e4763c68cb/